﻿using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using CapstoneProject.Models;
using System.Linq;

namespace CapstoneProject.Activities
{
    [Activity(Label = "ZhaoA_Capstone Project", MainLauncher = true, Icon = "@drawable/icon")]
    public class HomeActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Home);

            Button loginButton = FindViewById<Button>(Resource.Id.LoginButton);
            loginButton.Click += Login;

            Button newUserButton = FindViewById<Button>(Resource.Id.NewUserButton);
            newUserButton.Click += delegate { StartActivity(typeof(NewUserActivity)); };
        }

        private void Login(object sender, EventArgs e)
        {
            TextView loginError = FindViewById<TextView>(Resource.Id.LoginErrors);
            EditText usernameField = FindViewById<EditText>(Resource.Id.UsernameField);
            EditText passwordField = FindViewById<EditText>(Resource.Id.PasswordField);
            if (String.IsNullOrEmpty(passwordField.Text) || String.IsNullOrEmpty(usernameField.Text))
            {
                loginError.Text = "All fields are required.";
            }
            else
            {
                User loginUser = ((CapstoneApplication)Application).UserRepository.GetAllUsers().FirstOrDefault(u => u.Username == usernameField.Text);
                if (loginUser != null)
                {
                    if (passwordField.Text == loginUser.Password)
                    {
                        Intent i = new Intent();
                        i.SetClass(this, typeof(ProfileActivity));
                        i.AddFlags(ActivityFlags.NewTask);
                        i.PutExtra("User", loginUser.Username);
                        StartActivity(i);
                    }
                    else
                    {
                        loginError.Text = "Incorrect password.";
                    }
                }
                else
                {
                    loginError.Text = "Username does not exist.";
                }
            }
        }
    }
}

